package com.tinusgraglin.enclusiv.datalayer.repos

import com.tinusgraglin.enclusiv.Util.Companion.toImageUrl
import com.tinusgraglin.enclusiv.datalayer.*
import com.tinusgraglin.enclusiv.datalayer.datasources.ArticleRemoteSource
import com.tinusgraglin.enclusiv.datalayer.datasources.PicsRemoteSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class ArticleRepo(
    private val articleRemoteSource: ArticleRemoteSource,
    private val picsRemoteSource: PicsRemoteSource
) {
    companion object {
        private var repo: ArticleRepo? = null

        fun initialize (articleRemoteSource: ArticleRemoteSource, picsRemoteSource: PicsRemoteSource) {
            repo = ArticleRepo(articleRemoteSource, picsRemoteSource)
        }

        fun get() : ArticleRepo {
            if (repo != null)
                return repo as ArticleRepo
            else
                throw IllegalStateException("Uninitialized")
        }
    }
    suspend fun getArticle(aid: Long): ShowedArticleProfile {
        return withContext(Dispatchers.Default) {
            fillShowedArticleProfile(
                withContext(Dispatchers.IO) {
                    articleRemoteSource.getArticle(aid)
                }
            )
        }
    }

    suspend fun postArticle(article: EditedArticle) : Long {
        return withContext(Dispatchers.IO) {
            articleRemoteSource.upload(article.authorId, article.title, article.content, article.imageIds)
        }
    }

    private val imageIndicatorRegex = Regex("<img src=\".*\" />\n")

    private fun splitAroundImages(contentWithImageIndicators: String) =
        contentWithImageIndicators.split(imageIndicatorRegex)

    private fun fillShowedArticleProfile(basicArticleProfile: BasicArticleProfile): ShowedArticleProfile {
        val contentSegments = splitAroundImages(basicArticleProfile.article)
        return ShowedArticleProfile(
            id = basicArticleProfile.id,
            title = basicArticleProfile.title,
            authorName = basicArticleProfile.author.name,
            authorId = basicArticleProfile.author.id,
            authorProfileImgUrl = toImageUrl("profile_img/image", basicArticleProfile.author.id),
            contentSegments = contentSegments,
            contentCombined = contentSegments.reduce { acc, s -> acc + s },
            imageUrls = basicArticleProfile.imageIds.map { toImageUrl("user_images/image", it) },
            articleStats = basicArticleProfile.stats.copy()
        )
    }
}